const app = getApp()
const pagePermission = require('../../utils/pagepermission.js')

Page({
  data: {
    planId: '',
    form: {
      plan_name: '',
      total_quantity: '',
      planned_start_time: '',
      planned_end_time: '',
      actual_start_time: '',
      actual_end_time: '',
      description: ''
    },
    loading: false,
    plan: null
  },

  onLoad(options) {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/edit-production-plan/edit-production-plan')) {
      return
    }
    
    if (options.id) {
      this.setData({
        planId: options.id
      })
      this.loadPlanDetail()
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  // 加载生产计划详情
  loadPlanDetail() {
    this.setData({ loading: true })
    
    app.request({
      url: '/getProductionPlanDetail',
      method: 'GET',
      data: { id: this.data.planId }
    }).then(res => {
      this.setData({ loading: false })
      if (res.code === 1) {
        const plan = res.data
        this.setData({
          plan: plan,
          form: {
            plan_name: plan.plan_name || '',
            total_quantity: plan.total_quantity || '',
            planned_start_time: plan.planned_start_time ? this.formatDate(plan.planned_start_time) : '',
            planned_end_time: plan.planned_end_time ? this.formatDate(plan.planned_end_time) : '',
            actual_start_time: plan.actual_start_time ? this.formatDate(plan.actual_start_time) : '',
            actual_end_time: plan.actual_end_time ? this.formatDate(plan.actual_end_time) : '',
            description: plan.description || ''
          }
        })
        
        wx.setNavigationBarTitle({
          title: '编辑生产计划'
        })
      } else {
        wx.showToast({
          title: res.msg || '加载失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      this.setData({ loading: false })
      console.error('加载生产计划详情失败:', err)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    })
  },

  // 格式化日期
  formatDate(timestamp) {
    if (!timestamp) return ''
    const date = new Date(timestamp * 1000)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  },

  // 输入框变化
  onInputChange(e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value
    this.setData({
      [`form.${field}`]: value
    })
  },

  // 日期选择
  onDateChange(e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value
    this.setData({
      [`form.${field}`]: value
    })
  },

  // 提交表单
  submitForm() {
    // 验证必填字段
    if (!this.data.form.plan_name) {
      wx.showToast({
        title: '请输入计划名称',
        icon: 'none'
      })
      return
    }

    if (!this.data.form.total_quantity) {
      wx.showToast({
        title: '请输入计划数量',
        icon: 'none'
      })
      return
    }

    this.setData({ loading: true })

    const formData = {
      id: this.data.planId,
      ...this.data.form
    }

    app.request({
      url: '/updateProductionPlan',
      method: 'POST',
      data: formData
    }).then(res => {
      this.setData({ loading: false })
      if (res.code === 1) {
        wx.showToast({
          title: '更新成功',
          icon: 'success'
        })
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        wx.showToast({
          title: res.msg || '更新失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      this.setData({ loading: false })
      console.error('更新生产计划失败:', err)
      wx.showToast({
        title: '更新失败',
        icon: 'none'
      })
    })
  }
})
